import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

const slice = createSlice({
  name: 'count',
  initialState: 0,
  reducers: {
    add: (state, action) => {
      console.log(state, action);
      return state + action.payload.value
    },
    sub: (state, action) => {
      return state - action.payload.value
    },
  },
  extraReducers: (builder) => {
    builder.addCase(addAsync.fulfilled, (state, action) => {
      return state + action.payload.value
    })
  }
})

export const addAsync = createAsyncThunk(
  'count/addAsync',
  async (data) => {
    const val = await new Promise((res ,rej) => {
      setTimeout(() => {
        res(data)
      }, data.time);
    })
    return val
  }
)

export const { add, sub } = slice.actions
export default slice.reducer